<?php

namespace App\Admin\Controllers;

use App\Admin\Requests\SettingStoreRequest;
use App\Facades\Setting;
use App\Models\Setting as SettingModel;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    public function index()
    {
        if (request()->expectsJson()) {
            $page = SettingModel::when(request('type'), function ($query) {
                $query->where('type', request('type'));
            })
                ->when(request('keyword'), function ($query) {
                    $query->where('name', 'like', '%' . request('keyword') . '%');
                })
                ->orderBy('type', 'asc')
                ->orderBy('id', 'asc')
                ->paginate(request('limit', 15));

            collect($page->items())->each(function ($item) {
                $item->setAppends(['call_at_php', 'call_at_tmpl']);
            });

            return $this->laytable($page->total(), $page->items());
        }
        return view('admin.setting.index', [
            'types' => Setting::types(),
        ]);
    }

    public function create()
    {
        return view('admin.setting.create_and_edit', [
            'types' => Setting::types(),
        ]);
    }

    public function store(SettingStoreRequest $request)
    {
        $data = $request->all();
        if (!empty($data['new_type'])) {
            $data['type'] = $data['new_type'];
        }
        if (!Setting::store($data)) {
            return $this->failure('添加失敗');
        }
        return $this->success('添加成功', [], 200, route('setting.index', '', false));
    }

    public function edit($id)
    {
        return view('admin.setting.create_and_edit', [
            'types' => Setting::types(),
            'row'   => Setting::row($id),
        ]);
    }

    public function update(Request $request)
    {
        if (!Setting::update($request->input('id'), $request->all())) {
            return $this->failure('修改失敗');
        }
        return $this->success('修改成功', [], 200, route('setting.index', '', false));
    }

    public function delete()
    {
        $id = request()->id ?? request()->input('id');
        if (empty($id)) {
            return $this->failure('未選擇');
        }
        if (!Setting::delete($id)) {
            return $this->failure('刪除失敗');
        }
        return $this->success('刪除成功');
    }
}
